package com.unmarshaller.propertiesunmarshaller.transformer;

import java.lang.reflect.Field;
import java.net.InetAddress;
import java.net.InetSocketAddress;

import javax.xml.crypto.dsig.TransformException;

import com.unmarshaller.propertiesunmarshaller.ITransformer;


/**
 * 网络地址类型转换赋值
 * @author hongxiao.z
 * @date	2013-10-21
 */
public class InetSocketAddressTransformer implements ITransformer
{
	@Override
	public void transformer(Field field, String value) throws TransformException {
		String[] parts = value.split(":");

		if (parts.length != 2)
		{
			throw new TransformException("value:" + value + " invalid, is not transformer --- " + field.getType().getSimpleName() + " to " + field.getName());
		}

		try
		{
			if ("*".equals(parts[0]))
			{
				field.set(null, new InetSocketAddress(Integer.parseInt(parts[1])));
				return;
			}
			else
			{
				InetAddress address = InetAddress.getByName(parts[0]);
				int port = Integer.parseInt(parts[1]);
				field.set(null, new InetSocketAddress(address, port));
				return;
			}
		}
		catch (Exception e)
		{
			throw new TransformException("value:" + value + " invalid, is not transformer --- " + field.getType().getSimpleName() + " to " + field.getName());
		}
	}
	
}
